package SpringFramework.SpringEL.service;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

@Service
@PropertySource("classpath:SpringFramework/SpringEL/resource/test.properties")
public class ValueService {
	// 注入普通字符串
	@Value("I love you！")
	private String normal;
	
	// 注入系统环境变量内容
	@Value("#{systemProperties['os.name']}")
	private String osName;
	
	// 注入表达式结果
	@Value("#{ T(java.lang.Math).random() * 100.0 }")
	private double randomNumber;
	
	// 注入其他bean属性
	@Value("#{refService.another}")
	private String fromAnother;
	
	// 注入文件资源
	@Value("classpath:SpringFramework/SpringEL/resource/test.txt")
	private Resource testFile;
	
	// 注入网络资源
	@Value("http://www.baidu.com")
	private Resource testUrl;
	
	// 注入配置文件属性
	// 注入配置配件需使用@PropertySource指定文件地址，若使用@Value注入，则要配置一个@PropertySourcesPlaceholderConfigurer的Bean。
	// 注意这里使用的是$，而不是#
	@Value("${book.name}")
	private String bookName;
	
	@Autowired
	private Environment environment;
	
	@Bean
	public static PropertySourcesPlaceholderConfigurer propertyConfigure() {
		return new PropertySourcesPlaceholderConfigurer();
	}
	
	public void outputResource() {
		try {
			System.out.println("normal：" + normal);
			System.out.println("osName：" + osName);
			System.out.println("randomNumber：" + randomNumber);
			System.out.println("fromAnother：" + fromAnother);
			System.out.println("testFile：" + IOUtils.toString(testFile.getInputStream(), "UTF-8"));
			System.out.println("testUrl：" + IOUtils.toString(testUrl.getInputStream(), "UTF-8"));
			System.out.println("bookName：" + bookName);
			System.out.println("book.author：" + environment.getProperty("book.author"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
